// packageDetail/pages/detail-search/index.js
import {
    getSearchHot,
    getSearchSuggest,
    getSearchResult
} from '../../../service/api_search'
import { playerStore } from '../../../store/index'
import debounce from '../../../utils/debounce'
import stringToNodes from '../../../utils/string2nodes'
const debounceGetSearchSuggest = debounce(getSearchSuggest, 300)

Page({

    /**
     * 页面的初始数据
     */
    data: {
        hotKeywords: [],
        suggestSongs: [],
        suggestSongsNodes: [],
        resultSongs: [],
        searchValue: ""
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 1.获取页面的数据
        this.getPageData()
    },

    getPageData() {
        getSearchHot().then(res => {
            this.setData({
                hotKeywords: res.result.hots
            })
        })
    },

    // 事件处理
    handleSearchChange: function (event) {
        // 1.获取输入的关键字
        const searchValue = event.detail

        // 2.保存关键字
        this.setData({
            searchValue
        })

        // 3.判断关键字为空字符的处理逻辑
        if (!searchValue.length) {
            this.setData({
                suggestSongs: [],
                resultSongs: []
            })
            // 这里还有取消这次 运算的方式 还是分不出哦的选择
            debounceGetSearchSuggest.cancel()
            return
        }

        // 4.根据关键字进行搜索
        debounceGetSearchSuggest(searchValue).then(res => {
            // if (!this.data.searchValue.length) {
            //   console.log("searchValue没有值")
            //   return
            // }

            // 1.获取建议的关键字歌曲
            const suggestSongs = res.result.allMatch
            this.setData({
                suggestSongs
            })
            if (!suggestSongs) return

            // 2.转成nodes节点
            const suggestKeywords = suggestSongs.map(item => item.keyword)
            const suggestSongsNodes = []
            for (const keyword of suggestKeywords) {
                const nodes = stringToNodes(keyword, searchValue)
                suggestSongsNodes.push(nodes)
            }
            this.setData({
                suggestSongsNodes
            })
        })
    },
    handleSearchAction: function () {
        // 保存一下searchValue
        console.log('123')
        const searchValue = this.data.searchValue
        getSearchResult(searchValue).then(res => {
            this.setData({
                resultSongs: res.result.songs
            })
        })
    },
    handleSongItemClick: function(event) {
        const index = event.currentTarget.dataset.index
        playerStore.setState("playListSongs", this.data.resultSongs)
        console.log(this.data.resultSongs)
        playerStore.setState("playListIndex", index)
    }
})